package com.chuangke.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuangke.admin.dao.mapper.SysUserRoleMapper;
import com.chuangke.admin.entity.SysUserRole;
import com.chuangke.admin.service.SysUserRoleService;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.common.event.file.FilePermissionChangeEvent;
import com.chuangke.common.idgen.IdManager;
import com.chuangke.common.utils.BusinessUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;
	@Autowired
	private ApplicationEventPublisher eventPublisher;

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_USER_ROLE, key = "'" + CacheKeyConstants.SYS_USER_ROLE + "'")
	@Transactional
	@Override
	public void deleteByUserId(String id) {
		sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getUserId, id));
		eventPublisher.publishEvent(new FilePermissionChangeEvent(this));

	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_USER_ROLE, key = "'" + CacheKeyConstants.SYS_USER_ROLE + "'")
	@Transactional
	@Override
	public void insert(List<SysUserRole> list) {
		for (SysUserRole sysUserRole : list) {
			if(BusinessUtil.isInsert(sysUserRole.getId())) {
				sysUserRole.setId(IdManager.nextId());
			}
			sysUserRoleMapper.insert(sysUserRole);
		}
		eventPublisher.publishEvent(new FilePermissionChangeEvent(this));
	}
	
	@Cacheable(cacheNames = CacheKeyConstants.SYS_USER_ROLE, key = "'" + CacheKeyConstants.SYS_USER_ROLE + "'")
	@Override
	public Map<String, List<SysUserRole>> findAll() {
		List<SysUserRole> allList = sysUserRoleMapper.selectList(new QueryWrapper<>());
		return allList.stream().collect(Collectors.groupingBy(SysUserRole::getUserId));
	}
	
	@Override
	public void deleteByUserIds(List<String> ids) {
		sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().in(SysUserRole::getUserId, ids));
		eventPublisher.publishEvent(new FilePermissionChangeEvent(this));
	}
	
	@Transactional
	@CacheEvict(cacheNames = CacheKeyConstants.SYS_USER_ROLE, key = "'" + CacheKeyConstants.SYS_USER_ROLE + "'")
	@Override
	public void deleteByRoleId(String roleId) {
		sysUserRoleMapper.delete(new QueryWrapper<SysUserRole>().lambda().eq(SysUserRole::getRoleId, roleId));
		eventPublisher.publishEvent(new FilePermissionChangeEvent(this));
	}

}
